package com.hank.controller;

import com.hank.dto.Area;
import com.hank.util.PinyinUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AdminDivisionSpider {

    public static void crawlAndSave() throws Exception {
        Document doc = Jsoup.connect("http://www.mca.gov.cn/article/sj/xzqh/2022/202201xzqh.html").get();
        Element table = doc.getElementsByClass("xl7025670").first();
        Elements rows = table.select("tr");

        List<Area> areas = new ArrayList<>();

        for (Element row : rows) {
            Elements tds = row.select("td");

            if (tds.size() >= 5) {
                String code = tds.get(0).text();
                String name = tds.get(1).text();
                String parentCode = tds.get(2).text();
                String fullName = tds.get(3).text();
                int level = Integer.parseInt(tds.get(4).text());

                String pinyin = getPinyin(name);
                String pinyinShort = getFirstSpell(name);

                Area area = new Area();
                area.setCode(code);
                area.setName(name);
                area.setParentCode(parentCode);
                area.setFullName(fullName);
                area.setLevel(level);
                area.setPinyin(pinyin);
                area.setPinyinShort(pinyinShort);
                areas.add(area);
                System.out.println(areas);
            }
        }
    }

    // 获取汉字对应的拼音全拼
    private static String getPinyin(String str) {
        return PinyinUtil.getPinyin(str);
    }

    // 获取汉字对应的拼音首字母
    private static String getFirstSpell(String str) {
        return PinyinUtil.getFirstSpell(str);
    }

    public static void main(String[] args) throws Exception {
        crawlAndSave();
    }
}